<?php
declare(strict_types=1);

namespace App\WebSocket\Chat;

use Swoft\WebSocket\Server\Annotation\Mapping\MessageMapping;
use Swoft\WebSocket\Server\Annotation\Mapping\WsController;
use Swoft\WebSocket\Server\Message\Message;
use Swoft\WebSocket\Server\Message\Request;
use Tool\AjaxReturn;

/**
 * 客服相关
 * Class ClientController
 * @package App\WebSocket\Chat
 * @WsController(prefix="client")
 */
class ClientController
{
    /**
     * 客服初始化
     * @MessageMapping(command="initChat")
     */
    public function initChat(Request $request): array
    {
        $fd = $request->getFd();


        $data = AjaxReturn::sendNativeData([
            'fd' => $fd
        ]);

        server()->broadcast(json_encode($data), [], [$request->getFd()]);

        return $data;
    }

    /**
     * @MessageMapping()
     * @param Request $request
     * @return Message
     */
    public function sendMessage(Request $request): array {

        $data = $request->getMessage()->getData();
        vdump($data);

        $data['cmd'] = 'server.receiveMessage';

        server()->broadcast(json_encode(AjaxReturn::sendData($data)), [$data['fd']], [$request->getFd()]);

        return AjaxReturn::sendData([]);
    }

    /**
     * 客服初始化
     * @MessageMapping(command="send")
     */
    public function send(Request $request): array
    {
        return [
            'msg' => '客户端发送消息了'
        ];
    }
}